import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/logger.dart';
import 'package:chatgreat/helper/platform.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart' as tts;
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../helper/constant.dart';
import '../../repo/model/mine_collection_model.dart';

class AudioPlayerController {
  List<String> audioSources = [];
  int currentAudioIndex = 0;

  late AudioPlayer player;
  late tts.FlutterTts flutterTts;

  Function()? onPlayStopped;
  Function()? onPlayCompletion;
  Function()? onPlayAudioStarted;
  Function(bool loading)? onPlayAudioLoading;

  final bool useRemoteAPI;

  AudioPlayerController({required this.useRemoteAPI}) {
    if (useRemoteAPI) {
      player = AudioPlayer();
      player.setVolume(1);
      player.onPlayerComplete.listen((event) {
        if (currentAudioIndex < audioSources.length) {
          playNextAudioForPlayer();
        } else {
          if (onPlayCompletion != null) {
            onPlayCompletion!();
          }
        }
      });
    } else {
      flutterTts = tts.FlutterTts();
      if (PlatformTool.isIOS()) {
        flutterTts.setSharedInstance(true);
        flutterTts.setIosAudioCategory(
          tts.IosTextToSpeechAudioCategory.playback,
          [
            tts.IosTextToSpeechAudioCategoryOptions.allowBluetooth,
            tts.IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
            tts.IosTextToSpeechAudioCategoryOptions.mixWithOthers,
          ],
        );
      }

      flutterTts.setStartHandler(() {
        if (onPlayAudioStarted != null) {
          onPlayAudioStarted!();
        }
      });

      flutterTts.setErrorHandler((msg) {
        Logger.instance.e('TTS error: $msg');
      });

      flutterTts.setCancelHandler(() {
        if (onPlayStopped != null) {
          onPlayStopped!();
        }
      });

      flutterTts.completionHandler = () {
        if (onPlayCompletion != null) {
          onPlayCompletion!();
        }
      };
    }
  }

  void dispose() {
    if (useRemoteAPI) {
      player.dispose();
    } else {
      flutterTts.stop();
    }
  }

  Future<void> playAudioWithMessageId(int id) async {
    await stop();

    if (useRemoteAPI) {
      if (onPlayAudioStarted != null) {
        onPlayAudioStarted!();
      }
      onPlayAudioLoading?.call(true);
      resetAudioSourcesForPlayer(await APIServer().textToVoice(id: id));
      onPlayAudioLoading?.call(false);
      playNextAudioForPlayer();
    }
  }

  Future<CollectionRecord?> playAudio(String text, int roomId) async {
    await stop();

    if (text.isEmpty) {
      return null;
    }

    if (useRemoteAPI) {
      if (onPlayAudioStarted != null) {
        onPlayAudioStarted!();
      }
      onPlayAudioLoading?.call(true);
      if (roomId == chatHomeRoomId) {
        resetAudioSourcesForPlayer(await APIServer().voiceChat(content: text));

        onPlayAudioLoading?.call(false);
        playNextAudioForPlayer();
      } else {
        var model = await APIServer().roleVoiceChat(content: text, roomId: roomId);
        resetAudioSourcesForPlayer([model.voiceUrl ?? '']);

        onPlayAudioLoading?.call(false);
        playNextAudioForPlayer();
        return model;
      }
    } else {
      flutterTts.speak(text);
    }

    return null;
  }

  Future<void> stop() async {
    if (useRemoteAPI) {
      await player.stop();
      if (onPlayStopped != null) {
        onPlayStopped!();
      }
    } else {
      await flutterTts.stop();
    }
  }

  Future<void> playNextAudioForPlayer() async {
    if (audioSources.isEmpty) {
      return;
    }

    if (currentAudioIndex >= audioSources.length) {
      return;
    }

    await player.setAudioContext(const AudioContext(
      iOS: AudioContextIOS(
        category: AVAudioSessionCategory.playback,
        options: [
          AVAudioSessionOptions.mixWithOthers,
        ],
      ),
    ));

    await player.play(UrlSource(audioSources[currentAudioIndex])).catchError((e) {
      if (onPlayStopped != null) {
        onPlayStopped!();
      }
    });
    currentAudioIndex++;
  }

  void resetAudioSourcesForPlayer(List<String> sources) {
    if (sources.length == 1 && isBlank(sources.first)) {
      return;
    }
    audioSources = sources;
    currentAudioIndex = 0;
  }
}

class EnhancedAudioPlayer extends StatelessWidget {
  final AudioPlayerController controller;
  final bool loading;
  final bool showAudioPlayer;
  const EnhancedAudioPlayer(
      {super.key, required this.controller, this.loading = false, this.showAudioPlayer = false});

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        const SizedBox(width: 2,),
        loading
            ? Row(
                children: [
                  Text('合成中',
                    style: TextStyle(
                      color: customColors.weakTextColor,
                      fontSize: 13,
                    ),
                  ),
                  const SizedBox(width: 8),
                  LoadingAnimationWidget.fourRotatingDots(
                    color: const Color(0xFF4F6CEF),
                    size: 16,
                  ),
                ],
              )
            : LoadingAnimationWidget.staggeredDotsWave(
                color: const Color(0xFF4F6CEF),
                size: 25,
              ),
        const SizedBox(width: 3,)
      ],
    );
  }
}
